import { NextRequest, NextResponse } from 'next/server';
import { getDb } from '@/lib/db';
import { getCurrentUser, isAdmin } from '@/middleware/auth';
import { AuthService } from '@/lib/auth';
import { Role, Permission, RolePermission } from '@/lib/db/auth-schema';

/**
 * 获取角色的权限列表
 */
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    // 验证管理员权限
    let currentUser = getCurrentUser(request);
    
    // 如果getCurrentUser没有返回用户信息，尝试直接验证token
    if (!currentUser) {
      const authHeader = request.headers.get('authorization');
      const cookieHeader = request.headers.get('cookie');
      let token: string | null = null;
      
      if (authHeader && authHeader.startsWith('Bearer ')) {
        token = authHeader.substring(7);
      } else if (cookieHeader) {
        const cookies = cookieHeader.split(';').reduce((acc: any, cookie) => {
          const [key, value] = cookie.trim().split('=');
          acc[key] = value;
          return acc;
        }, {});
        token = cookies['auth-token'] || null;
      }
      
      if (token) {
        const tokenResult = await AuthService.verifyToken(token);
        if (tokenResult.valid && tokenResult.payload) {
          currentUser = tokenResult.payload;
        }
      }
    }
    
    if (!currentUser || !isAdmin(currentUser)) {
      return NextResponse.json(
        { success: false, error: '权限不足' },
        { status: 403 }
      );
    }

    const { id: roleId } = await params;
    const db = await getDb();

    // 检查角色是否存在
    const roleResult = await db.findOne<Role>('roles', { id: roleId });
    const role = roleResult.success ? roleResult.data : null;

    if (!role) {
      return NextResponse.json(
        { success: false, error: '角色不存在' },
        { status: 404 }
      );
    }

    // 获取所有权限
    const allPermissionsResult = await db.findMany<Permission>('permissions', { is_active: 1 });
    const allPermissions = allPermissionsResult.success ? allPermissionsResult.data || [] : [];

    // 获取角色已分配的权限（简化版本，这里返回空数组）
    const rolePermissionsResult = await db.findMany<RolePermission>('role_permissions', { role_id: roleId });
    const rolePermissions = rolePermissionsResult.success ? rolePermissionsResult.data || [] : [];
    const assignedPermissionIds = rolePermissions.map(rp => rp.permission_id);

    // 标记权限是否已分配给角色
    const permissionsWithStatus = allPermissions.map(permission => ({
      ...permission,
      assigned: assignedPermissionIds.includes(permission.id),
      assignedAt: rolePermissions.find(rp => rp.permission_id === permission.id)?.granted_at || null
    }));

    // 按类别分组
    const permissionsByCategory = permissionsWithStatus.reduce((acc: any, permission) => {
      const category = permission.category || 'other';
      if (!acc[category]) {
        acc[category] = [];
      }
      acc[category].push(permission);
      return acc;
    }, {});

    return NextResponse.json({
      success: true,
      data: {
        role,
        permissions: permissionsWithStatus,
        permissionsByCategory,
        stats: {
          total: allPermissions.length,
          assigned: assignedPermissionIds.length,
          unassigned: allPermissions.length - assignedPermissionIds.length
        }
      }
    });

  } catch (error) {
    console.error('获取角色权限失败:', error);
    return NextResponse.json(
      { success: false, error: '获取角色权限失败' },
      { status: 500 }
    );
  }
}

/**
 * 更新角色权限配置
 */
export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    // 验证管理员权限
    let currentUser = getCurrentUser(request);
    
    // 如果getCurrentUser没有返回用户信息，尝试直接验证token
    if (!currentUser) {
      const authHeader = request.headers.get('authorization');
      const cookieHeader = request.headers.get('cookie');
      let token: string | null = null;
      
      if (authHeader && authHeader.startsWith('Bearer ')) {
        token = authHeader.substring(7);
      } else if (cookieHeader) {
        const cookies = cookieHeader.split(';').reduce((acc: any, cookie) => {
          const [key, value] = cookie.trim().split('=');
          acc[key] = value;
          return acc;
        }, {});
        token = cookies['auth-token'] || null;
      }
      
      if (token) {
        const tokenResult = await AuthService.verifyToken(token);
        if (tokenResult.valid && tokenResult.payload) {
          currentUser = tokenResult.payload;
        }
      }
    }
    
    if (!currentUser || !isAdmin(currentUser)) {
      return NextResponse.json(
        { success: false, error: '权限不足' },
        { status: 403 }
      );
    }

    const { id: roleId } = await params;
    const body = await request.json();
    const { permissionIds } = body;

    if (!Array.isArray(permissionIds)) {
      return NextResponse.json(
        { success: false, error: '权限ID列表格式错误' },
        { status: 400 }
      );
    }

    const db = await getDb();

    // 检查角色是否存在
    const roleResult = await db.findOne<Role>('roles', { id: roleId });
    const role = roleResult.success ? roleResult.data : null;

    if (!role) {
      return NextResponse.json(
        { success: false, error: '角色不存在' },
        { status: 404 }
      );
    }

    // 检查是否为系统角色（系统角色权限不允许修改）
    if (role.is_system) {
      return NextResponse.json(
        { success: false, error: '系统角色权限不允许修改' },
        { status: 403 }
      );
    }

    // 验证权限ID是否存在
    const validPermissions: Permission[] = [];
    for (const permissionId of permissionIds) {
      const permissionResult = await db.findOne<Permission>('permissions', { id: permissionId });
      if (permissionResult.success && permissionResult.data) {
        validPermissions.push(permissionResult.data);
      }
    }

    if (validPermissions.length !== permissionIds.length) {
      return NextResponse.json(
        { success: false, error: '部分权限ID无效' },
        { status: 400 }
      );
    }

    // 删除角色现有的所有权限关联
    const existingRolePermissions = await db.findMany<RolePermission>('role_permissions', { role_id: roleId });
    if (existingRolePermissions.success && existingRolePermissions.data) {
      for (const rp of existingRolePermissions.data) {
        await db.delete('role_permissions', { id: rp.id });
      }
    }

    // 创建新的权限关联
    const now = new Date().toISOString();
    const newRolePermissions: RolePermission[] = [];

    for (const permission of validPermissions) {
      const rolePermissionId = `rp_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
      const rolePermissionData: Partial<RolePermission> = {
        id: rolePermissionId,
        role_id: roleId,
        permission_id: permission.id,
        granted_at: now,
        granted_by: currentUser.userId
      };

      const createResult = await db.create<RolePermission>('role_permissions', rolePermissionData);
      if (createResult.success && createResult.data) {
        newRolePermissions.push(createResult.data);
      }
    }

    return NextResponse.json({
      success: true,
      data: {
        role,
        assignedPermissions: validPermissions,
        rolePermissions: newRolePermissions
      },
      message: `成功为角色 ${role.display_name} 配置了 ${validPermissions.length} 个权限`
    });

  } catch (error) {
    console.error('更新角色权限失败:', error);
    return NextResponse.json(
      { success: false, error: '更新角色权限失败' },
      { status: 500 }
    );
  }
}

/**
 * 批量配置角色权限
 */
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    // 验证管理员权限
    let currentUser = getCurrentUser(request);
    
    // 如果getCurrentUser没有返回用户信息，尝试直接验证token
    if (!currentUser) {
      const authHeader = request.headers.get('authorization');
      const cookieHeader = request.headers.get('cookie');
      let token: string | null = null;
      
      if (authHeader && authHeader.startsWith('Bearer ')) {
        token = authHeader.substring(7);
      } else if (cookieHeader) {
        const cookies = cookieHeader.split(';').reduce((acc: any, cookie) => {
          const [key, value] = cookie.trim().split('=');
          acc[key] = value;
          return acc;
        }, {});
        token = cookies['auth-token'] || null;
      }
      
      if (token) {
        const tokenResult = await AuthService.verifyToken(token);
        if (tokenResult.valid && tokenResult.payload) {
          currentUser = tokenResult.payload;
        }
      }
    }
    
    if (!currentUser || !isAdmin(currentUser)) {
      return NextResponse.json(
        { success: false, error: '权限不足' },
        { status: 403 }
      );
    }

    const { id: roleId } = await params;
    const body = await request.json();
    const { permissionIds } = body;

    if (!Array.isArray(permissionIds)) {
      return NextResponse.json(
        { success: false, error: '权限ID列表格式错误' },
        { status: 400 }
      );
    }

    const db = await getDb();

    // 检查角色是否存在
    const roleResult = await db.findOne<Role>('roles', { id: roleId });
    const role = roleResult.success ? roleResult.data : null;

    if (!role) {
      return NextResponse.json(
        { success: false, error: '角色不存在' },
        { status: 404 }
      );
    }

    // 验证权限ID是否存在
    const validPermissions: Permission[] = [];
    for (const permissionId of permissionIds) {
      const permissionResult = await db.findOne<Permission>('permissions', { id: permissionId });
      if (permissionResult.success && permissionResult.data) {
        validPermissions.push(permissionResult.data);
      }
    }

    if (validPermissions.length !== permissionIds.length) {
      return NextResponse.json(
        { success: false, error: '部分权限ID无效' },
        { status: 400 }
      );
    }

    // 删除角色现有的所有权限关联
    const existingRolePermissions = await db.findMany<RolePermission>('role_permissions', { role_id: roleId });
    if (existingRolePermissions.success && existingRolePermissions.data) {
      for (const rp of existingRolePermissions.data) {
        await db.delete('role_permissions', { id: rp.id });
      }
    }

    // 创建新的权限关联
    const now = new Date().toISOString();
    const newRolePermissions: RolePermission[] = [];

    for (const permission of validPermissions) {
      const rolePermissionId = `rp_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
      const rolePermissionData: Partial<RolePermission> = {
        id: rolePermissionId,
        role_id: roleId,
        permission_id: permission.id,
        granted_at: now,
        granted_by: currentUser.userId
      };

      const createResult = await db.create<RolePermission>('role_permissions', rolePermissionData);
      if (createResult.success && createResult.data) {
        newRolePermissions.push(createResult.data);
      }
    }

    return NextResponse.json({
      success: true,
      data: {
        role,
        assignedPermissions: validPermissions,
        rolePermissions: newRolePermissions
      },
      message: `成功为角色 ${role.display_name} 配置了 ${validPermissions.length} 个权限`
    });

  } catch (error) {
    console.error('分配角色权限失败:', error);
    return NextResponse.json(
      { success: false, error: '分配角色权限失败' },
      { status: 500 }
    );
  }
}